package com.demo.control;

import com.alibaba.fastjson.JSON;
import com.demo.annotation.ValidResult;
import com.demo.base.BaseController;
import com.demo.model.Country;
import com.demo.model.common.MsgMap;
import com.demo.service.CountryService;
import com.demo.util.LoggerUtils;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.Filter;
import javax.validation.*;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.*;

/**
 * User: lwb
 * Date: 2017/10/17
 * Time: 14:31
 * function:
 */
@Controller
@RequestMapping("/country")
public class CountryController  extends BaseController{

    @Autowired
    CountryService countryService;

    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    @RequestMapping(value = "test0")
    @ResponseBody
    public MsgMap test0() throws NoSuchFieldException, IllegalAccessException {
        System.out.println("-----------------charset:" + Charset.defaultCharset());

        Map<String , Filter> map = shiroFilterFactoryBean.getFilters();
        Iterator<Map.Entry<String, Filter>> iterator = map.entrySet().iterator();
        while(iterator.hasNext())
        {
            Map.Entry<String , Filter> entry = iterator.next();
            System.out.println("filterName:" + entry.getKey());
//			NameableFilter f = (NameableFilter) entry.getValue();
        }


        MsgMap msg = this.getMsgMap();
        msg.put("test" , "testvalue");
        msg.putMsg("lalalala");
        return msg;
    }

    @RequestMapping(value = "test1")
    @ResponseBody
    public String test1() throws NoSuchFieldException, IllegalAccessException {
        System.out.println("-----------------charset:" + Charset.defaultCharset());
        return "{aaa:'你好'}";
    }


    @RequestMapping("test")
    @ResponseBody
    public MsgMap test()
    {
        MsgMap msg = this.getMsgMap();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Country country = new Country();
        Set<ConstraintViolation<Country>> constraintViolations = validator.validate(country);
        for (ConstraintViolation<Country> constraintViolation : constraintViolations) {
            String message = constraintViolation.getMessage();
            msg.put(constraintViolation.getPropertyPath().toString(), message);
        }
        return msg;
    }

    @RequestMapping("create")
    @ResponseBody
    public MsgMap create(@Valid Country country , @ValidResult BindingResult result)
    {
        if(result.hasErrors())
        {
            LoggerUtils.debug(JSON.toJSONString(getErrors(result)));
            return this.getMsgMap();
        }

        MsgMap msg = this.getMsgMap();
        countryService.create(country);
        return msg;
    }

    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<String, String>();
        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
            System.out.println("error.getField():" + error.getField());
            System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());

            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }

    @RequestMapping("create1")
    @ResponseBody
    public MsgMap create1(Country country)
    {
        MsgMap msg = this.getMsgMap();
        countryService.create1();
        return msg;
    }

    @RequestMapping("update")
    @ResponseBody
    public MsgMap update(Country country)
    {
        MsgMap msg = this.getMsgMap();
        countryService.update(country);
        return msg;
    }

    @RequestMapping("delete")
    @ResponseBody
    public MsgMap delete(Country country)
    {
        MsgMap msg = this.getMsgMap();
        countryService.delete(country);
        return msg;
    }

    @RequestMapping("list")
    @ResponseBody
    public Map list(Country country,
                       @RequestParam(required = false, defaultValue = "2") int page,
                       @RequestParam(required = false, defaultValue = "2") int rows)
    {
        MsgMap msg = this.getMsgMap();
        List<Country> list =  countryService.selectByCountry(country , page , rows);
        PageInfo<Country> pageInfo = new PageInfo<>(list);
        msg.put("pageInfo" , pageInfo);
        Map map = new HashMap<String , Object>();
        map.put("resultMsg", "ok");
        map.put("resultCode" , 200);
        map.put("data" , pageInfo.getList());
        map.put("page" , pageInfo.getPageNum());
        map.put("allPage" , pageInfo.getPages());
        return map;
    }

}
